import { GitLocation } from './locator'
import { run, RunOptions } from './shell'

export interface GitCommandOptions {
  readonly env?: Record<string, any>
  cwd?: string
  readonly encoding?: BufferEncoding | 'buffer' | string
}

export function gitcmd<T extends string | Buffer>(
  opts: GitCommandOptions,
  gitLocation: GitLocation,
  ...args: string[]
): Promise<T> {
  const runOpts: RunOptions = {
    ...opts,
    encoding: (opts.encoding ?? 'utf8') === 'utf8' ? 'utf8' : 'buffer',
    // Adds GCM environment variables to avoid any possible credential issues -- from https://github.com/Microsoft/vscode/issues/26573#issuecomment-338686581
    // Shouldn't *really* be needed but better safe than sorry
    env: {
      ...process.env,
      ...(opts.env ?? {}),
      GCM_INTERACTIVE: 'NEVER',
      GCM_PRESERVE_CREDS: 'TRUE',
      LC_ALL: 'C',
    },
  }
  const promise = run<T>(gitLocation.path, args, opts.encoding ?? 'utf8', runOpts)
  return promise
}
